import { createRouter, createWebHistory, type RouteComponent } from 'vue-router'

import remainingRouter from './modules/static'
import { initRouter, sortAsyncRoutes } from './utils'
import { getToken, removeToken } from '@/utils/auth'
import { usePermissionStore } from '@/stores/modules/permission'
import { cloneDeep } from 'lodash'
import type { App } from 'vue'
const modules = import.meta.glob(['./modules/**/*.ts', '!./modules/static.ts'], { eager: true })
// /** 原始静态路由（未做任何处理） */
// const routes = []
const routes: any = []

/** 路由白名单 */
const whiteList = ['/login']

Object.keys(modules).forEach((key) => {
  routes.push((modules[key] as any).default)
})
export const constantMenus: Array<RouteComponent> = sortAsyncRoutes(
  cloneDeep(routes).flat(Infinity)
).concat(...remainingRouter)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: sortAsyncRoutes(routes.concat(...remainingRouter))
})

router.beforeEach((to, from, next) => {
  document.title = (to.meta.title || '') as string
  if (getToken()) {
    if (usePermissionStore().wholeMenus.length === 0 && to.path !== '/login') {
      initRouter().then(async () => {
        router.push(to.fullPath)
        next(false) // 阻止当前导航，因为已经手动处理了
      })
    }
    next()
  } else {
    if (to.path !== '/login') {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        removeToken()
        next({ path: '/login' })
      }
    } else {
      next()
    }
  }
})
export default router

export function setupRouter(app: App<Element>) {
  app.use(router)
}
